package com.idol.logger.core.printer.window.adapt

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.idol.logger.R
import com.idol.logger.core.printer.data.LoggerMo

internal abstract class IdolAdaptProxy(private val inflater: LayoutInflater) {
    class Holder(val root: View) {
        val label: TextView? by lazy { root.findViewById(R.id.tag) }
        val content: TextView? by lazy { root.findViewById(R.id.message) }
        val line: View? by lazy { root.findViewById(R.id.line) }
    }

    private val dataList = arrayListOf<LoggerMo>()

    abstract fun notifyChangedItemInserted(position: Int)

    fun add(data: LoggerMo) = also {
        dataList.add(data)
        notifyChangedItemInserted(dataList.size - 1)
    }

    fun onCreateViewHolder(parent: ViewGroup) = Holder(
        inflater.inflate(R.layout.idol_item, parent, false)
    )

    fun count(): Int = dataList.size

    fun onBindViewHolder(holder: Holder, position: Int) {
        val data = dataList[position]
        val color = highlightColor(data.level)
        holder.label?.also {
            it.setTextColor(color)
            it.text = data.flattened()
        }
        holder.content?.also {
            it.setTextColor(color)
            it.text = data.message
        }

        holder.line?.also {
            if (position == 0) {
                it.visibility = View.GONE
            } else {
                it.visibility = View.VISIBLE
            }
        }
    }

    // 根据log级别获取不同的高亮颜色.
    private fun highlightColor(level: Int): Int = when (level) {
        Log.VERBOSE -> 0xffbbbbbb.toInt()
        Log.DEBUG -> 0xffffffff.toInt()
        Log.INFO -> 0xff6a8759.toInt()
        Log.WARN -> 0xffbbb529.toInt()
        Log.ERROR -> 0xffff6b68.toInt()
        Log.ASSERT -> 0xffffff00.toInt()
        else -> 0xffbbbbbb.toInt()
    }
}
